package com.heima.app.gateway.filters;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.function.Consumer;

//@Order(0)
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //1、要获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2、从请求中获取请求路径
        String path = request.getURI().getPath();
        //2.1  判断如果是登录请求，则直接放行
        if (path.contains("login_auth")) {
            return chain.filter(exchange);
        }

        //3、如果不是登录请求，应该从请求中获取到token
        String token = request.getHeaders().getFirst("token");

        //3.1  如果token不存在，返回错误码(401),并结束本次请求
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.2 如果token存在，但校验失败，也要响应401，并结束本次请求
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            //获取token中的用户id
            Object id = claimsBody.get("id");
            //修改请求头
            request=request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId",String.valueOf(id));
                }
            }).build();

            //修改exchange
            exchange = exchange.mutate().request(request).build();

        } catch (Exception ex) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.3 token验证成功，直接放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
